package com.inspur.humantask.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.xcc.cache.CacheManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Component
@Aspect
public class LogProcessAop {

	private Logger logger= LoggerFactory .getLogger(LogProcessAop.class);
	
	 //	@Pointcut("execution(* com.inspur.humantask.web.TaskCommonController.saveTaskData(..))")
	 /*	@Pointcut("execution(* com.inspur.humantask.service.SyncService.testKey(..))")
	    public void pointCut() {
	    }
	*/
	 	
	/* 	 @Around("pointCut()")*/
	
	
	@Value("${urlJson}")
	String urlJson;
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	//	@Around("pointCut()")
	     public String action(ProceedingJoinPoint pjp) throws Throwable {
	 		 Object[] args=pjp.getArgs();
	 		/* for(Object arg:args) {
	 			 System.out.println(arg);
	 		 }*/
	 		//	humanTaskId="1968016921968640";
	 		 
	 		/* new Thread(()->{
		 			RestTemplate postIPNetworkarea= new RestTemplate();
					String url=urlJson+args[1]+"";
					System.out.println(url);
					ResponseEntity<String> response= postIPNetworkarea.getForEntity(url, String.class);
					rooms=JSONObject.parseObject(response.getBody());
		 		 }).start();*/
	 		 
	 		//捞数据
	 		 
	 		 
	 		
	 	//	String mFromJsonDateSql="select * from scidc.form_data_info where id=1965365257371648";
		//	 List<Map<String, Object>>  mFromJsonDate=jdbcTemplate.queryForList(mFromJsonDateSql);
	 		String mFromJsonDateSql="select * from scidc.form_data_info where id="+args[0];
	 		List<Map<String, Object>>  mFromJsonDate=	 (List<Map<String, Object>>) CacheManager.get(args[0]+"");
	 		 
	 		 JSONObject rooms;
	 		/* new Thread(()->{
	 			logger.info(Thread.currentThread().getName()+":开始");
	 			
	 			
	 			
	 		 }).start();*/
	 		 
	 		String str= (String) pjp.proceed();
	 		 
	 		System.out.println(urlJson);
	 		
	 		
	 		 new Thread(()->{
	 			 
	 			 
	 			logger.info(Thread.currentThread().getName()+"后");
	 			//新老json
	 				JSONObject mFormJsonOld =  JSONObject.parseObject((String) mFromJsonDate.get(0).get("form_json"));
	 				
	 			//	System.out.println("form_json:"+mFormJsonOld);
	 				
	 				JSONObject mFormJsonlast = JSONObject.parseObject((String) jdbcTemplate.queryForList(mFromJsonDateSql).get(0).get("form_json"));
	 				 
	 				String  processId=(String) mFromJsonDate.get(0).get("flow_id");
	 				
	 				String sqltaskInfoId="select ID id,assignee from scidc.task_info where process_instance_id="+processId+" ORDER BY claim_time desc ";
	 				String taskInfoId=jdbcTemplate.queryForList(sqltaskInfoId).get(1).get("id")+"";
	 				String	assignId= jdbcTemplate.queryForList(sqltaskInfoId).get(1).get("assignee")+"";
		 		 
					String bussinKeySql= "select KEY_ from  scidc.act_re_procdef WHERE ID_=(select PROC_DEF_ID_ from scidc.ACT_HI_PROCINST  where PROC_INST_ID_= "+processId+")";
					System.out.println(bussinKeySql);
					String key=jdbcTemplate.queryForList(bussinKeySql, String.class).get(0);

					String keyConfig="select * from scidc.t_dic_flow_log where dic_type='"+key+"'";
					System.out.println(keyConfig);
					List<Map<String, Object>> mconfigs=jdbcTemplate.queryForList(keyConfig) ;
					for(Map arg:mconfigs) {
						
						if((arg.get("dic_key")+"").indexOf(":")==-1) {
							String valueOld=(String) mFormJsonOld.get(arg.get("dic_key"));
							String valueNew=(String) mFormJsonlast.get(arg.get("dic_key"));
							valueOld=StringUtils.isEmpty(valueOld)?"":valueOld;
							valueNew=StringUtils.isEmpty(valueNew)?"":valueNew;
							if(!valueOld.equals(valueNew)) {
								String sql="insert into scidc.process_log (oldvalue,lastvalue,taskInfoId,assignId,fieldName,field,processInstanceId,fieldType,configId) values (\'"
										+ valueOld+"\',\'"+valueNew+"\',"+taskInfoId+","+assignId+",\'"+arg.get("dic_value")+"\',\'"+arg.get("dic_key")+"\',\'"+processId+"\'"+","+(StringUtils.isEmpty(arg.get("dic_key")+"")?"0":"1")+","+arg.get("id")+""
										+ ")";
								logger.info(sql);
								jdbcTemplate.execute(sql);
							}
						}else {
							
						//	String valueOldJson=(String) mFormJsonOld.get(arg.get("dic_key"));
						//	String valueNewJson=(String) mFormJsonlast.get(arg.get("dic_key"));
							
							String valueOld=(String) mFormJsonOld.get((arg.get("dic_key")+"").split(":")[0]);
							String valueNew=(String) mFormJsonlast.get((arg.get("dic_key")+"").split(":")[0]);
							if(!valueOld.equals(valueNew)) {
								String sql="insert into scidc.process_log (oldvalue,lastvalue,taskInfoId,assignId,fieldName,field,processInstanceId,fieldType,configId) values (\'"
										+ valueOld+"\',\'"+valueNew+"\',"+taskInfoId+","+assignId+",\'"+arg.get("dic_value")+"\',\'"+arg.get("dic_key")+"\',\'"+processId+"\'"+","+"3"+","+arg.get("id")+""
										+ ")";
								logger.info(sql);
								jdbcTemplate.execute(sql);
							}
						}
						
					}
					
					
					//新增fileName 监控
					String oldvalue=	 (String) CacheManager.get(args[0]+"fileOld");
					String valueNew=	 (String) CacheManager.get(args[0]+"fileNew");
				    keyConfig="select * from scidc.t_dic_flow_log where dic_type='"+key+"'"+"and  dic_key='file'";
					System.out.println(keyConfig);
					 mconfigs=jdbcTemplate.queryForList(keyConfig) ;
				 
					
					String sql="insert into scidc.process_log (oldvalue,lastvalue,taskInfoId,assignId,fieldName,field,processInstanceId,fieldType,configId) values (\'"
							+ oldvalue+"\',\'"+valueNew+"\',"+taskInfoId+","+assignId+",\'"+"上传文件"+"\',\'"+"file"+"\',\'"+processId+"\'"+","+"0"+","+mconfigs.get(0).get("id")+""
				+ ")";
					jdbcTemplate.execute(sql);
					System.out.println(mconfigs.toString());
		 	}).start();
	 		 return str;
	 	 } 
	
	
	  
	
}
